package com.kpx.app.wigdet;

/**
 * 参考DatePickWheelDialog
 */

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.kpx.app.R;
import com.kpx.app.wigdet.NumberPicker.OnPickerLayoutChangeListener;
import com.kpx.app.wigdet.NumberPicker.OnValueChangeListener;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

public class TimePickDialog extends BaseDialog implements OnValueChangeListener {
    protected static final int MSG_RECOMPUTE_DIVIDER_POSITION = 0;
    protected static Activity mContext;
    private final View.OnClickListener dismissListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            dismiss();
        }
    };
    protected int START_YEAR = 1900, END_YEAR = 2100;
    protected int NOW_YEAR = 2100, NOW_MOUTH = 12, NOW_DAY = 1;
    protected ImageView topDivider;
    protected ImageView bottomDivider;
    protected NumberPicker wv_year;
    protected NumberPicker wv_month;
    protected NumberPicker wv_day;
    protected NumberPicker wv_hours;
    protected NumberPicker wv_mins;
    protected String[] months_big = {"1", "3", "5", "7", "8", "10", "12"};
    protected final List<String> list_big = Arrays.asList(months_big);
    protected String[] months_little = {"4", "6", "9", "11"};
    protected final List<String> list_little = Arrays.asList(months_little);
    protected String[] minutes_values = {"0", "10", "20", "30", "40", "50"};
    protected Button btn_sure;
    protected CharSequence positiveText;
    protected Button btn_cancel;
    protected CharSequence negativeText;
    protected CharSequence titleText;
    protected Calendar calendar;
    protected View.OnClickListener positiveClickListener;
    protected View.OnClickListener negativeClickListener;
    protected boolean showYear, showMonth, showDay, showHour, showMins;

    @SuppressLint("HandlerLeak")
    protected Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_RECOMPUTE_DIVIDER_POSITION:
                    if (Build.VERSION.SDK_INT > 11) {
                        topDivider.setY(msg.arg1);
                        bottomDivider.setY(msg.arg2);
                    } else {
                        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                        params.topMargin = msg.arg1; // Your Y coordinate
                        topDivider.setLayoutParams(params);

                        params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                        params.topMargin = msg.arg2; // Your Y coordinate
                        bottomDivider.setLayoutParams(params);
                    }
                    break;
            }
        }

    };
    private View container_year;
    private View container_month;
    private View container_day;
    private View container_hour;
    private View container_minute;

    protected TimePickDialog(Context context) {
        super(context);
    }

    protected TimePickDialog(Context context, Calendar instance) {
        this(context);
        calendar = instance;
    }

    public static long getFormatTime(Calendar c) {
        String parten = "00";
        DecimalFormat decimal = new DecimalFormat(parten);
        // 设置日期的显示
        Calendar calendar = c;
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        return calendar.getTimeInMillis();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.setContentView(R.layout.time_picker_dlg_layout);
        setEndDate();
        findView();
        adjustView();
        setListener();
        setDate(calendar);
        // 自定义代码在这里
        onCustomDisplayType();
    }

    protected void setEndDate() {
        try {
            Calendar cd = Calendar.getInstance();
            NOW_YEAR = cd.get(Calendar.YEAR);
            END_YEAR = NOW_YEAR;
            Log.v("tag", "END_YEAR----------" + END_YEAR);
            NOW_MOUTH = cd.get(Calendar.MONTH) + 1;
            Log.v("tag", "NOW_MOUTH----------" + NOW_MOUTH);
            NOW_DAY = cd.get(Calendar.DATE);
            Log.v("tag", "NOW_DAY----------" + NOW_DAY);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void onCustomDisplayType() {

    }

    private void adjustView() {
        // // 根据屏幕密度来指定选择器字体的大小
        // int textSize = 0;
        //
        // textSize = pixelsToDip(mContext.getResources(), 13);
        // wv_day.TEXT_SIZE = textSize;
        // wv_hours.TEXT_SIZE = textSize;
        // wv_mins.TEXT_SIZE = textSize;
        // wv_month.TEXT_SIZE = textSize;
        // wv_year.TEXT_SIZE = textSize;
    }

    private void setListener() {
        wv_year.setOnValueChangedListener(this);
        wv_month.setOnValueChangedListener(this);
        // 取消
        if (negativeClickListener != null) {
            btn_cancel.setOnClickListener(negativeClickListener);
        } else {
            btn_cancel.setOnClickListener(dismissListener);
        }
        if (positiveClickListener != null) {
            btn_sure.setOnClickListener(positiveClickListener);
        } else {
            btn_sure.setOnClickListener(dismissListener);
        }
    }

    private void findView() {
        container_year = findViewById(R.id.linearLayout_picker_year);
        wv_year = (NumberPicker) findViewById(R.id.numberPicker_year);
        wv_year.setMaxValue(END_YEAR);
        wv_year.setMinValue(START_YEAR);
        wv_year.setFocusable(true);
        wv_year.setFocusableInTouchMode(true);
        wv_year.setOnValueChangedListener(this);

        container_month = findViewById(R.id.linearLayout_picker_month);
        wv_month = (NumberPicker) findViewById(R.id.numberPicker_month);
        wv_month.setMaxValue(12);
        wv_month.setMinValue(1);
        wv_month.setFocusable(true);
        wv_month.setFocusableInTouchMode(true);
        wv_month.setOnValueChangedListener(this);

        container_day = findViewById(R.id.linearLayout_picker_day);
        wv_day = (NumberPicker) findViewById(R.id.numberPicker_day);
        wv_day.setMaxValue(31);
        wv_day.setMinValue(1);
        wv_day.setFocusable(true);
        wv_day.setFocusableInTouchMode(true);

        container_hour = findViewById(R.id.linearLayout_picker_hour);
        wv_hours = (NumberPicker) findViewById(R.id.numberPicker_hour);
        wv_hours.setMaxValue(23);
        wv_hours.setMinValue(0);
        wv_hours.setFocusable(true);
        wv_hours.setFocusableInTouchMode(true);

        container_minute = findViewById(R.id.linearLayout_picker_minute);
        wv_mins = (NumberPicker) findViewById(R.id.numberPicker_minute);
        wv_mins.setDataFormat(true);
        wv_mins.setMinValue(0);
        wv_mins.setMaxValue(59);
        wv_mins.setFocusable(true);
        wv_mins.setFocusableInTouchMode(true);

        setShowDate(showYear, showMonth, showDay, showHour, showMins);

        wv_year.setOnPickerLayoutChangeListener(new OnPickerLayoutChangeListener() {
            @Override
            public void deviderPostionYCallback(int topDividerY, int bottomDividerY) {
                Message msg = new Message();
                msg.what = MSG_RECOMPUTE_DIVIDER_POSITION;
                msg.arg1 = topDividerY;
                msg.arg2 = bottomDividerY;
                handler.sendMessage(msg);
            }
        });
        topDivider = (ImageView) findViewById(R.id.picker_bg_divider_top);
        bottomDivider = (ImageView) findViewById(R.id.picker_bg_divider_bottom);

        // 自动填充区域
        final RelativeLayout layout = (RelativeLayout) findViewById(R.id.linearLayout_pickers_container);
        layout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                LayoutParams rlParamsTop = (LayoutParams) topDivider.getLayoutParams();
                rlParamsTop.width = layout.getWidth();
                topDivider.setLayoutParams(rlParamsTop);

                LayoutParams rlParamsBottom = (LayoutParams) bottomDivider.getLayoutParams();
                rlParamsBottom.width = layout.getWidth();
                bottomDivider.setLayoutParams(rlParamsBottom);

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }

            }
        });

        btn_sure = (Button) findViewById(R.id.date_select_button_right);
        if (positiveText != null) {
            btn_sure.setVisibility(View.VISIBLE);
            btn_sure.setText(positiveText);
        }
        btn_cancel = (Button) findViewById(R.id.date_select_button_left);
        if (negativeText != null) {
            btn_cancel.setVisibility(View.VISIBLE);
            btn_cancel.setText(negativeText);
        }

        TextView title = (TextView) findViewById(R.id.title);
        title.setText(titleText);
    }

    @Override
    public void setTitle(CharSequence title) {
        titleText = title;
    }

    private void setPositiveButton(CharSequence mPositiveButtonText, View.OnClickListener onClickListener) {
        positiveText = mPositiveButtonText;
        positiveClickListener = onClickListener;// can't use btn_sure here
        // because it's on defined yet
    }

    private void setNegativeButton(CharSequence mNegativeButtonText, View.OnClickListener onClickListener) {
        negativeText = mNegativeButtonText;
        negativeClickListener = onClickListener;// can't use btn_sure here
        // because it's on defined yet
    }

    private void setCalendar(Calendar calendar) {
        this.calendar = calendar;
    }

    public TimePickDialog setDate(Calendar calendar) {
        if (calendar == null)
            return this;
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        wv_year.setValue(year);// 初始化时显示的数据
        wv_month.setValue(month + 1);
        wv_day.setValue(day);
        calcDataChanged();
        wv_hours.setValue(hour);
        wv_mins.setValue(minute);
        return this;
    }

    public Calendar getSetCalendar() {
        Calendar c = Calendar.getInstance();
        c.set(wv_year.getValue(), wv_month.getValue() - 1, wv_day.getValue(), wv_hours.getValue(), wv_mins.getValue());
        return c;
    }

    /**
     * 计算数据变动
     */
    private void calcDataChanged() {
        int year_num = wv_year.getValue();
        int month_num = wv_month.getValue();
        // 判断是不是当前日期 如果是则不能大于这个日期
        /*if (year_num == END_YEAR) {
            wv_month.setMaxValue(NOW_MOUTH);
			if (month_num == NOW_MOUTH) {
				wv_day.setMinValue(1);
				wv_day.setMaxValue(NOW_DAY);
			} else {
				// 判断大小月及是否闰年,用来确定"日"的数据
				if (list_big.contains(String.valueOf(month_num))) {
					wv_day.setMinValue(1);
					wv_day.setMaxValue(31);
				} else if (list_little.contains(String.valueOf(month_num))) {
					wv_day.setMinValue(1);
					wv_day.setMaxValue(30);
				} else {
					if ((year_num % 4 == 0 && year_num % 100 != 0)
							|| year_num % 400 == 0) {
						wv_day.setMinValue(1);
						wv_day.setMaxValue(29);
					} else {
						wv_day.setMinValue(1);
						wv_day.setMaxValue(28);
					}
				}
			}
		} else {
			wv_month.setMaxValue(12);

			// 判断大小月及是否闰年,用来确定"日"的数据
			if (list_big.contains(String.valueOf(month_num))) {
				wv_day.setMinValue(1);
				wv_day.setMaxValue(31);
			} else if (list_little.contains(String.valueOf(month_num))) {
				wv_day.setMinValue(1);
				wv_day.setMaxValue(30);
			} else {
				if ((year_num % 4 == 0 && year_num % 100 != 0)
						|| year_num % 400 == 0) {
					wv_day.setMinValue(1);
					wv_day.setMaxValue(29);
				} else {
					wv_day.setMinValue(1);
					wv_day.setMaxValue(28);
				}
			}
		}*/

        wv_month.setMaxValue(12);

        // 判断大小月及是否闰年,用来确定"日"的数据
        if (list_big.contains(String.valueOf(month_num))) {
            wv_day.setMinValue(1);
            wv_day.setMaxValue(31);
        } else if (list_little.contains(String.valueOf(month_num))) {
            wv_day.setMinValue(1);
            wv_day.setMaxValue(30);
        } else {
            if ((year_num % 4 == 0 && year_num % 100 != 0) || year_num % 400 == 0) {
                wv_day.setMinValue(1);
                wv_day.setMaxValue(29);
            } else {
                wv_day.setMinValue(1);
                wv_day.setMaxValue(28);
            }
        }

    }

    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        if (picker == wv_year || picker == wv_month) {
            calcDataChanged();
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        mContext = null;
    }

    /**
     * 设置显示时间
     *
     * @param showYear  是否显示年
     * @param showMonth 是否显示月份
     * @param showDay   是否小时日
     * @param showHour  是否显示小时
     * @param showMins  是否显示分钟
     */
    private void setShowDate(boolean showYear, boolean showMonth, boolean showDay, boolean showHour, boolean showMins) {
        container_year.setVisibility(showYear ? View.VISIBLE : View.GONE);
        wv_year.setVisibility(showYear ? View.VISIBLE : View.GONE);
        container_month.setVisibility(showMonth ? View.VISIBLE : View.GONE);
        wv_month.setVisibility(showMonth ? View.VISIBLE : View.GONE);
        container_day.setVisibility(showDay ? View.VISIBLE : View.GONE);
        wv_day.setVisibility(showDay ? View.VISIBLE : View.GONE);
        container_hour.setVisibility(showHour ? View.VISIBLE : View.GONE);
        wv_hours.setVisibility(showHour ? View.VISIBLE : View.GONE);
        container_minute.setVisibility(showMins ? View.VISIBLE : View.GONE);
        wv_mins.setVisibility(showMins ? View.VISIBLE : View.GONE);
    }

    public static class Builder {
        private final DatePickParams P;

        public Builder(Context context) {
            mContext = (Activity) context;
            mContext.setTheme(R.style.SampleTheme_Light_WrapWidth);
            P = new DatePickParams(context);
        }

        public Builder(Context context, Calendar calendar) {
            mContext = (Activity) context;
            mContext.setTheme(R.style.SampleTheme_Light_WrapWidth);
            P = new DatePickParams(context, calendar);
        }

        public Builder setTitle(CharSequence title) {
            P.mTitle = title;
            return this;
        }

        public Builder setIcon(int iconId) {
            P.mIconId = iconId;
            return this;
        }

        public Builder setPositiveButton(CharSequence text, final View.OnClickListener listener) {
            P.mPositiveButtonText = text;
            P.mPositiveButtonListener = listener;
            return this;
        }

        public Builder setNegativeButton(CharSequence text, final View.OnClickListener listener) {
            P.mNegativeButtonText = text;
            P.mNegativeButtonListener = listener;
            return this;
        }

        public Builder setShowDate(boolean showYear, boolean showMonth, boolean showDay, boolean showHour, boolean showMins) {
            P.showYear = showYear;
            P.showMonth = showMonth;
            P.showDay = showDay;
            P.showHour = showHour;
            P.showMins = showMins;
            return this;
        }

        public TimePickDialog create() {
            final TimePickDialog dialog = new TimePickDialog(P.mContext);
            P.apply(dialog);
            return dialog;
        }
    }

    public static class DatePickParams {
        public final Context mContext;
        public int mIconId;
        public View.OnClickListener mPositiveButtonListener;
        public CharSequence mPositiveButtonText;
        public CharSequence mTitle;
        public Calendar calendar;
        protected CharSequence mNegativeButtonText;
        protected View.OnClickListener mNegativeButtonListener;
        protected boolean showYear, showMonth, showDay, showHour, showMins;

        public DatePickParams(Context context) {
            mContext = context;
            calendar = Calendar.getInstance();
        }

        public DatePickParams(Context context, Calendar calendar) {
            mContext = context;
            this.calendar = calendar;
        }

        public void apply(TimePickDialog dialog) {
            if (mTitle != null) {
                dialog.setTitle(mTitle);
            }
            if (mPositiveButtonText != null) {
                dialog.setPositiveButton(mPositiveButtonText, mPositiveButtonListener);
            }
            if (mNegativeButtonText != null) {
                dialog.setNegativeButton(mNegativeButtonText, mNegativeButtonListener);
            }
            if (calendar != null) {
                dialog.setCalendar(calendar);
            }
            dialog.showYear = showYear;
            dialog.showMonth = showMonth;
            dialog.showDay = showDay;
            dialog.showHour = showHour;
            dialog.showMins = showMins;
        }
    }
}
